<template>
  <div class="videos">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-background">
        <el-carousel height="100%" indicator-position="outside" arrow="always" :autoplay="true" :interval="5000" :key="firstImagesKey">
          <el-carousel-item v-for="(img, idx) in firstImages" :key="idx">
            <img :src="img" alt="视频课程背景" class="header-bg-image" @click="handleHeroImageClick(idx, img)" style="cursor: pointer;" />
          </el-carousel-item>
        </el-carousel>
        <div class="header-overlay"></div>
      </div>
      <div class="header-content">
        <h1>{{ $t('videos.title') }}</h1>
        <p>{{ $t('videos.subtitle') }}</p>
      </div>
    </div>

    <!-- 筛选器 -->
    <div class="filters-section">
      <div class="container">
        <div class="filters">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-select v-model="selectedCategory" placeholder="选择分类" @change="filterVideos">
                <el-option label="全部" value="all" />
                <el-option label="特定技能" value="tokutei" />
                <el-option label="日语学习" value="japanese" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="selectedLevel" placeholder="选择级别" @change="filterVideos">
                <el-option label="全部级别" value="all" />
                <el-option label="初级" value="beginner" />
                <el-option label="中级" value="intermediate" />
                <el-option label="高级" value="advanced" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-input 
                v-model="searchKeyword" 
                placeholder="搜索视频..." 
                @input="filterVideos"
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="filterVideos">
                {{ $t('common.search') }}
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <!-- 视频网格 -->
    <div class="videos-section">
      <div class="container">
        <div class="videos-grid">
          <div 
            v-for="video in filteredVideos" 
            :key="video.id" 
            class="video-card"
            @click="playVideo(video)"
          >
            <!--<div class="video-thumbnail">-->
              <!--<img :src="video.thumbnail" :alt="video.title" />-->
              <!--<div class="video-overlay">-->
                <!--<el-icon :size="40"><VideoPlay /></el-icon>-->
              <!--</div>-->
              <!--<div class="video-duration">{{ formatDuration(video.duration) }}</div>-->
            <!--</div>-->
            
            <div class="video-info">
              <h3>{{ video.title }}</h3>
              <p class="video-description">{{ video.description }}</p>
              
              <div class="video-meta">
                <div class="video-stats">
                  <span class="views">{{ video.views }} 次观看</span>
                  <span class="date">{{ formatDate(video.uploadDate) }}</span>
                </div>
                
                <div class="video-tags">
                  <el-tag size="small" :type="getTagType(video.category)">
                    {{ video.category }}
                  </el-tag>
                  <el-tag size="small" type="info">
                    {{ video.level }}
                  </el-tag>
                </div>
              </div>
              
              <div class="video-instructor">
                <el-avatar :size="24" :src="video.instructor.avatar" />
                <span>{{ video.instructor.name }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 36, 48]"
            :total="totalVideos"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 视频播放对话框 -->
    <el-dialog 
      v-model="videoDialogVisible" 
      :title="currentVideo?.title"
      width="80%"
      :before-close="closeVideoDialog"
    >
      <div v-if="currentVideo" class="video-player-container">
        <div class="video-player">
          <!-- 视频播放器 -->
          <div v-if="isVideoPlaying" class="video-iframe-container">
            <!--<div class="video-controls">-->
              <!--<el-button -->
                <!--type="primary" -->
                <!--size="small" -->
                <!--@click="stopVideo"-->
                <!--class="back-button"-->
              <!--&gt;-->
                <!--<el-icon><ArrowLeft /></el-icon>-->
                <!--返回-->
              <!--</el-button>-->
            <!--</div>-->
              <video class="video-iframe" v-if="currentVideo.videoUrl" :src="resolveUrl(currentVideo.videoUrl)" controls style="width: 100%; max-height: 420px; background: #000;" />

              <!--<iframe-->
              <!--:src="baseUrl +currentVideo.videoUrl"-->
              <!--frameborder="0"-->
              <!--allowfullscreen-->
              <!--class="video-iframe"-->
            <!--&gt;</iframe>-->
          </div>
          
          <!-- 视频占位符 -->
          <div v-else class="video-placeholder">
            <!--<img :src="currentVideo.thumbnail" :alt="currentVideo.title" class="video-preview" />-->
            <div class="play-button">
              <el-icon :size="60"><VideoPlay /></el-icon>
            </div>
            <p class="video-url">{{ currentVideo.videoUrl }}</p>
          </div>
        </div>
          <div class="video-other" v-if="currentVideo.jumpUrl">
              <text class="video-other-text">外部链接: </text><a :href="currentVideo.jumpUrl" target="_blank" >{{ currentVideo.jumpUrl }}</a>
          </div>
        
        <div class="video-details">
          <div class="video-header">
            <h2>{{ currentVideo.title }}</h2>
            <!--<div class="video-actions">-->
              <!--<el-button type="primary" @click="likeVideo">-->
                <!--<el-icon><Star /></el-icon>-->
                <!--点赞 ({{ currentVideo.likes }})-->
              <!--</el-button>-->
              <!--<el-button @click="shareVideo">-->
                <!--<el-icon><Share /></el-icon>-->
                <!--分享-->
              <!--</el-button>-->
            <!--</div>-->
          </div>
          
          <!--<div class="video-stats">-->
            <!--<span>{{ currentVideo.views }} 次观看</span>-->
            <!--<span>{{ formatDate(currentVideo.uploadDate) }}</span>-->
            <!--<span>{{ formatDuration(currentVideo.duration) }}</span>-->
          <!--</div>-->
          
          <div class="video-description-full">
            <p>{{ currentVideo.description }}</p>
          </div>
          
          <div class="video-instructor-full">
            <el-avatar :size="40" :src="currentVideo.instructor.avatar" />
            <div class="instructor-info">
              <h4>{{ currentVideo.instructor.name }}</h4>
              <p>{{ currentVideo.instructor.bio }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  VideoPlay, 
  Star, 
  Share,
  ArrowLeft
} from '@element-plus/icons-vue'
import {
  getVideosList,
  getVideoDetail,
} from '@/api/system'

const { t } = useI18n()
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const imageObj = computed(() => userStore.imageObj)

// 轮播图片处理
const firstImages = computed(() => {
  const raw = imageObj?.value?.firstUrl
  if (!raw) {
    return ['/src/assets/index/study.jpg']
  }
  // 支持字符串数组或逗号分隔字符串
  let list = Array.isArray(raw) ? raw : String(raw).split(',')
  list = list.map(s => String(s).trim()).filter(Boolean)
  const resolved = list.map(url => {
    if (/^https?:\/\//i.test(url)) return url
    return (import.meta.env.VITE_BASE_URL || '') + url
  })
  return resolved.length ? resolved : ['/src/assets/index/study.jpg']
})
const firstImagesKey = computed(() => firstImages.value.join('|'))

// 轮播图片点击处理
const handleHeroImageClick = (index, url) => {
  // 这里可以根据业务进行跳转或埋点
  // 先占位实现点击事件
  // console.log('clicked hero image:', index, url)
}

// 响应式数据
const selectedCategory = ref('all')
const selectedLevel = ref('all')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const videoDialogVisible = ref(false)
const currentVideo = ref(null)
const isVideoPlaying = ref(false)
const loading = ref(false)
const totalVideos = ref(0)
const videos = ref([])
// 兼容相对地址
const resolveUrl =(url)=> {
  if (!url) return ''
  if (/^https?:\/\//i.test(url)) return url
  return (import.meta.env.VITE_BASE_URL || '') + url
}
//const baseUrl = import.meta.env.VITE_BASE_URL
// 获取视频课程列表
const fetchVideos = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      category: selectedCategory.value !== 'all' ? selectedCategory.value : '',
      level: selectedLevel.value !== 'all' ? selectedLevel.value : '',
      keyword: searchKeyword.value
    }
    
    const response = await getVideosList(params)
    if (response.code === 200) {
      videos.value = response.rows || []
      totalVideos.value = response.total || 0
    } else {
      ElMessage.error(response.msg || '获取视频课程列表失败')
    }
  } catch (error) {
    console.error('获取视频课程列表失败:', error)
    ElMessage.error('获取视频课程列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取视频课程详情
const fetchVideoDetail = async (videoId) => {
  try {
    const response = await getVideoDetail(videoId)
    if (response.code === 200) {
      return response.data
    } else {
      ElMessage.error(response.msg || '获取视频课程详情失败')
      return null
    }
  } catch (error) {
    console.error('获取视频课程详情失败:', error)
    ElMessage.error('获取视频课程详情失败，请稍后重试')
    return null
  }
}

// 计算属性
const filteredVideos = computed(() => {
  let filtered = videos.value

  // 按分类筛选
  if (selectedCategory.value !== 'all') {
    filtered = filtered.filter(v => v.category === selectedCategory.value)
  }

  // 按级别筛选
  if (selectedLevel.value !== 'all') {
    filtered = filtered.filter(v => v.level === selectedLevel.value)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    filtered = filtered.filter(v => 
      v.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      v.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  if(filtered.length>0){
    filtered.forEach(r=>{
      if(r.instructor && typeof r.instructor == 'string'){
        r.instructor = JSON.parse(r.instructor)
      }
    })
  }
  return filtered
})

// 移除这个计算属性，因为我们现在从API获取总数

// 方法
const formatDuration = (seconds) => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const getTagType = (category) => {
  const typeMap = {
    '特定技能': 'primary',
    '日语学习': 'success'
  }
  return typeMap[category] || 'info'
}

const filterVideos = () => {
  currentPage.value = 1
  fetchVideos()
}

const playVideo = async (video) => {
  try {
    // 获取完整的视频课程详情
    const videoDetail = await fetchVideoDetail(video.id)
    if (videoDetail) {
      if(videoDetail.instructor && typeof videoDetail.instructor == 'string'){
        videoDetail.instructor = JSON.parse(videoDetail.instructor)
      }
      currentVideo.value = videoDetail
      videoDialogVisible.value = true
      // 直接开始播放视频
      isVideoPlaying.value = true
    }
  } catch (error) {
    console.error('获取视频课程详情失败:', error)
  }
}

const playVideoUrl = () => {
  if (currentVideo.value && currentVideo.value.videoUrl) {
    // 在当前区域播放视频
    isVideoPlaying.value = true
  } else {
    ElMessage.warning('视频链接不可用')
  }
}

const stopVideo = () => {
  isVideoPlaying.value = false
}

const closeVideoDialog = () => {
  videoDialogVisible.value = false
  currentVideo.value = null
  isVideoPlaying.value = false
}

const likeVideo = async () => {
  if (currentVideo.value) {
    try {
      // 这里应该调用点赞接口
      // const response = await likeVideo(currentVideo.value.id)
      // if (response.code === 200) {
      //   currentVideo.value.likes++
      //   ElMessage.success('点赞成功！')
      // }
      
      // 暂时模拟点赞成功
      currentVideo.value.likes++
      ElMessage.success('点赞成功！')
    } catch (error) {
      console.error('点赞失败:', error)
      ElMessage.error('点赞失败，请稍后重试')
    }
  }
}

const shareVideo = async () => {
  if (currentVideo.value) {
    try {
      // 这里应该调用分享接口
      // const response = await shareVideo(currentVideo.value.id)
      // if (response.code === 200) {
      //   ElMessage.success('分享成功！')
      // }
      
      // 暂时模拟分享成功
      ElMessage.success('分享成功！')
    } catch (error) {
      console.error('分享失败:', error)
      ElMessage.error('分享失败，请稍后重试')
    }
  }
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchVideos()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchVideos()
}

onMounted(() => {
  // 初始化数据
  fetchVideos()
})
</script>

<style scoped>
.videos {
  min-height: 100vh;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 页面头部 */
.page-header {
  position: relative;
  height: 300px;
  display: flex;
  align-items: center;
  color: white;
  overflow: hidden;
}

.header-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.el-carousel {
  height: 100%;
}

.header-bg-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.header-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(44, 62, 80, 0.3), rgba(52, 73, 94, 0.3));
}

.header-content {
  position: relative;
  z-index: 2;
  width: 80%;
    margin: auto;
  text-align: center;
}

.header-content h1 {
  font-size: 3rem;
  font-weight: bold;
  margin-bottom: 15px;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
}

.header-content p {
  font-size: 1.2rem;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}

/* 筛选器区域 */
.filters-section {
  background: #f8f9fa;
  padding: 30px 0;
  border-bottom: 1px solid #e9ecef;
}

.filters {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

/* 视频区域 */
.videos-section {
  padding: 40px 0;
  background: white;
}

.videos-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 30px;
  margin-bottom: 40px;
}

.video-card {
  background: white;
  border-radius: 15px;
  overflow: hidden;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
}

.video-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.video-thumbnail {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.video-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.video-card:hover .video-thumbnail img {
  transform: scale(1.05);
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
}

.video-card:hover .video-overlay {
  opacity: 1;
}

.video-duration {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.video-info {
  padding: 20px;
}

.video-info h3 {
  font-size: 1.2rem;
  color: #2c3e50;
  margin-bottom: 10px;
  line-height: 1.4;
}

.video-description {
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.video-stats {
  display: flex;
  gap: 15px;
  font-size: 0.9rem;
  color: #999;
}

.video-tags {
  display: flex;
  gap: 5px;
}

.video-instructor {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.9rem;
  color: #666;
}

/* 视频播放对话框 */
.video-player-container {
  max-height: 70vh;
  overflow-y: auto;
}

.video-player {
  margin-bottom: 20px;
}

.video-iframe-container {
  width: 100%;
  border-radius: 10px;
  overflow: hidden;
  /*aspect-ratio: 16/9;*/
    height: 300px;
  background: #000;
  position: relative;
}

.video-controls {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
}

.back-button {
  background: rgba(0, 0, 0, 0.7);
  border: none;
  color: white;
}

.back-button:hover {
  background: rgba(0, 0, 0, 0.9);
}

.video-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.video-placeholder {
  position: relative;
  background: #000;
  border-radius: 10px;
  overflow: hidden;
  /*aspect-ratio: 5/2;*/
    height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.video-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.7);
  border-radius: 50%;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background 0.3s ease;
}

.play-button:hover {
  background: rgba(0, 0, 0, 0.9);
}

.video-url {
  position: absolute;
  bottom: 10px;
  left: 10px;
  font-size: 0.8rem;
  opacity: 0.7;
}

.video-other-text{
    font-size: 14px;
    font-weight: 700;
    display: inline-block;
    margin-right: 10px;
}

.video-details {
  padding: 20px 0;
}

.video-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.video-header h2 {
  font-size: 1.5rem;
  color: #2c3e50;
  margin: 0;
  flex: 1;
  margin-right: 20px;
}

.video-actions {
  display: flex;
  gap: 10px;
}

.video-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  font-size: 0.9rem;
  color: #666;
}

.video-description-full {
  margin-bottom: 20px;
}

.video-description-full p {
  color: #666;
  line-height: 1.6;
}

.video-instructor-full {
  display: flex;
  gap: 15px;
  align-items: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 10px;
}

.instructor-info h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
}

.instructor-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content h1 {
    font-size: 2rem;
  }
  
  .header-content p {
    font-size: 1rem;
  }
  
  .videos-grid {
    grid-template-columns: 1fr;
  }
  
  .video-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .video-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .video-actions {
    width: 100%;
    justify-content: center;
  }
}
</style> 